package com.yww.utils;

import com.yww.entity.Users;
import com.yww.service.UsersService;
import sun.misc.BASE64Decoder;

import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.UUID;


public class PhotoUtil {

    //base64字符串转化成图片
    public static String GenerateImage(String imgStr, Integer userId, UsersService usersService) {   //对字节数组字符串进行Base64解码并生成图片

        if (imgStr == null) //图像数据为空
            return "";
        BASE64Decoder decoder = new BASE64Decoder();
        try {
            //Base64解码
            byte[] b = decoder.decodeBuffer(imgStr);
            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {//调整异常数据
                    b[i] += 256;
                }
            }
            //重命名
            String name = UUID.randomUUID().toString().replaceAll("-", "");
            String fileName = "img/"+name + ".png";
            //生成jpeg图片
            String imgFilePath = "G:\\hb\\manager\\" +fileName;//新生成的图片
            //更新数据库
            Users u = new Users();
            u.setUserId(userId);
            u.setImgUrl(fileName);
            usersService.updateById(u);
            OutputStream out = new FileOutputStream(imgFilePath);
            out.write(b);
            out.flush();
            out.close();
            return fileName;
        } catch (Exception e) {
            return "";
        }
    }
}
